<template>
  <div id="app">
    <div class="todo-container">
      <div class="todo-wrap">
        <Top :todos="todos" @add_item="add_item" />
        <List :todos="todos" />
        <Footer :todos="todos" @check_all_todos="check_all_todos" @clear_all="clear_all" />
      </div>
    </div>
  </div>
</template>

<script>
import Top from './components/Top.vue'
import List from './components/List.vue'
import Footer from './components/Footer.vue'

export default {
  name: 'App',
  data() {
    return {
      todos: JSON.parse(localStorage.getItem("todos")) || [],
    }
  },
  components: {
    Top,
    List,
    Footer,
  },
  methods: {
    add_item(item) {
      this.todos.unshift(item)
    },
    check_todo(id) {
      this.todos.forEach(e => {
        if (e.id === id) e.done = !e.done
      })
    },
    check_all_todos(check) {
      this.todos.forEach(e => e.done = check)
    },
    clear_all() {
      this.todos = this.todos.filter(e => !e.done)
    }
  },
  mounted() {
    this.$bus.$on("check_todo", this.check_todo)
    this.$bus.$on("del_todo", (id) => {
      this.todos = this.todos.filter(e => e.id !== id)
    })
    this.$bus.$on("updata_todo", (id, value) => {
      this.todos.forEach(e => {
        e.id === id ? e.title = value : null
      })
    })
  },
  beforeDestroy() {
    this.$bus.$off(["check_todo", "del_todo", "updata_todo"])
  },
  watch: {
    todos: {
      deep: true,
      handler(value) {
        localStorage.setItem("todos", JSON.stringify(value))
      }
    }
  }
}
</script>

<style lang="less">
body {
  background: #fff;
}

.btn {
  display: inline-block;
  padding: 4px 12px;
  margin-bottom: 0;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.btn-danger {
  color: #fff;
  background-color: #da4f49;
  border: 1px solid #bd362f;
}

.btn-edit {
  color: #fff;
  background-color: #64e7e1;
  border: 1px solid #3897a8;
  margin-right: 5px;
}

.btn-danger:hover {
  color: #fff;
  background-color: #bd362f;
}

.btn:focus {
  outline: none;
}

.todo-container {
  width: 600px;
  margin: 0 auto;
}

.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>